package com.glls.customer.config;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import reactor.core.publisher.Mono;

/**
 * TODO
 *
 * @author junyang
 * @version 1.0.0
 * @date 2025/2/19 14:42
 */
public class CustomLoadBalancer implements ReactorServiceInstanceLoadBalancer {


    private final String serviceId;
    private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;
    public CustomLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId) {
        this.serviceId = serviceId;

        this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
    }

    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {

        ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider.getIfAvailable();

        return supplier.get().next()
                .map(serviceInstances -> {
                    if (serviceInstances.isEmpty()) {
                        return new EmptyResponse();
                    }
                    // 自定义选择逻辑，例如根据某些属性过滤或排序
                    ServiceInstance instance = serviceInstances.get(0); // 示例：选择第一个实例
                    return new DefaultResponse(instance);
                });
    }
}
